//
//  ViewController.m
//  XLSlideMenuExample
//
//  Created by MengXianLiang on 2017/5/8.
//  Copyright © 2017年 MengXianLiang. All rights reserved.
//

#import "ViewController.h"
#import "XLSlideMenu.h"
#import "CustomAnnotationView.h"
#import "POIAnnotation.h"
#import "CCLocationManager.h"

#import "QuickStartAnnotationView.h"

@interface ViewController () <MAMapViewDelegate,AMapSearchDelegate> {
    MAMapView *mapView_;
}

//搜索
@property (nonatomic, strong) AMapSearchAPI *search;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = @"成都市";
    
    //左
    UIImageView *headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 37, 37)];
    headerImageView.layer.cornerRadius = headerImageView.bounds.size.width/2.0f;
    headerImageView.layer.masksToBounds = true;
    headerImageView.image = [UIImage imageNamed:@"header"];
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showLeft)];
    [headerImageView addGestureRecognizer:tap1];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:headerImageView];
    
    //右
    UIImageView *moreImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
    moreImageView.image = [UIImage imageNamed:@"more"];
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showRight)];
    [moreImageView addGestureRecognizer:tap2];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:moreImageView];
    

    
    //初始化地图
    mapView_ = [[MAMapView alloc] initWithFrame:self.view.bounds];
    
    mapView_.delegate = self;
    
    mapView_.showTraffic = YES;         //显示交通状况
    
    mapView_.showsCompass = NO;
    
    mapView_.showsScale = NO;
    
    [self.view addSubview:mapView_];
    
    //定位
    mapView_.showsUserLocation = YES;
    
    mapView_.userTrackingMode = MAUserTrackingModeFollow;
    
    [mapView_ setZoomLevel:16.145280 animated:YES];

    //初始化POI
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
    
    [[CCLocationManager shareLocation] getLocationCoordinate:^(CLLocationCoordinate2D locationCorrrdinate) {
        AMapPOIAroundSearchRequest *poiAround = [[AMapPOIAroundSearchRequest alloc] init];
        poiAround.location = [AMapGeoPoint locationWithLatitude:locationCorrrdinate.latitude longitude:locationCorrrdinate.longitude];
        poiAround.keywords = @"停车场";
        poiAround.sortrule            = 0;
        poiAround.requireExtension = YES;
        [self.search AMapPOIAroundSearch:poiAround];
    }];
    
    //修改级别
    UIView *zoomPannelView = [self makeZoomPannelView];
    zoomPannelView.center = CGPointMake(self.view.bounds.size.width -  CGRectGetMidX(zoomPannelView.bounds) - 10,
                                        self.view.bounds.size.height -  CGRectGetMidY(zoomPannelView.bounds) - 225);
    
    zoomPannelView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
    [self.view addSubview:zoomPannelView];
    
    
    //添加搜索
    UIImage *image_search = [UIImage imageNamed:@"搜索相关"];
    UIImageView *imageView_s = [[UIImageView alloc] initWithImage:image_search];
    imageView_s.frame = CGRectMake((YBKAppFrame.size.width - image_search.size.width)/2.0, YBKAppFrame.size.height - 64 - image_search.size.height, image_search.size.width, image_search.size.height);
    [self.view addSubview:imageView_s];
    

}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    

}

-(void)addAnnotationWithCooordinate:(CLLocationCoordinate2D)coordinate
{
    MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
    annotation.coordinate = coordinate;
    annotation.title    = @"AutoNavi";
    annotation.subtitle = @"CustomAnnotationView";
    
    [mapView_ addAnnotation:annotation];
}

- (UIView *)makeZoomPannelView
{
    UIView *ret = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 53, 98)];
    
    UIButton *incBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 53, 49)];
    [incBtn setImage:[UIImage imageNamed:@"increase"] forState:UIControlStateNormal];
    [incBtn sizeToFit];
    [incBtn addTarget:self action:@selector(zoomPlusAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *decBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 49, 53, 49)];
    [decBtn setImage:[UIImage imageNamed:@"decrease"] forState:UIControlStateNormal];
    [decBtn sizeToFit];
    [decBtn addTarget:self action:@selector(zoomMinusAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    [ret addSubview:incBtn];
    [ret addSubview:decBtn];
    
    return ret;
}

- (void)zoomPlusAction
{
    CGFloat oldZoom = mapView_.zoomLevel;
    [mapView_ setZoomLevel:(oldZoom + 1) animated:YES];
}

- (void)zoomMinusAction
{
    CGFloat oldZoom = mapView_.zoomLevel;
    [mapView_ setZoomLevel:(oldZoom - 1) animated:YES];
}

-(void)showLeft{
    [self.xl_sldeMenu showLeftViewControllerAnimated:true];
}

-(void)showRight{
    [self.xl_sldeMenu showRightViewControllerAnimated:true];
}

- (MAAnnotationView*)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *customReuseIndetifier = @"customReuseIndetifier";
        
        CustomAnnotationView *annotationView = (CustomAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        
        if (annotationView == nil)
        {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            // must set to NO, so we can show the custom callout view.
            annotationView.canShowCallout = NO;
            annotationView.draggable = YES;
            annotationView.calloutOffset = CGPointMake(0, -5);
        }
        
        annotationView.portrait = [UIImage imageNamed:@"hema"];
        annotationView.name     = @"河马";
        
        return annotationView;
    }else if ([annotation isKindOfClass:[MAUserLocation class]]) {
        static NSString *customReuseIndetifier = @"userlocation";
        MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
        }
        
        annotationView.image = [UIImage imageNamed:@"自己所在位置图标"];
        return annotationView;
    }else if([annotation isKindOfClass:[POIAnnotation class]]){
        static NSString *customReuseIndetifier = @"POIlocation";
        QuickStartAnnotationView *annotationView = (QuickStartAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[QuickStartAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
        }
        
        annotationView.image = [UIImage imageNamed:@"停车位"];
        annotationView.canShowCallout = YES;
        
//        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [btn setBackgroundImage:[UIImage imageNamed:@"导航"] forState:UIControlStateNormal];
//        
//        annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        
        return annotationView;
    }
    
    return nil;
}

-(void)mapView:(MAMapView *)mapView annotationView:(MAAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
    id<MAAnnotation> annotation = view.annotation;

    if ([annotation isKindOfClass:[POIAnnotation class]]) {
        NSLog(@"准备导航");
        //导航
        POIAnnotation *pp = (POIAnnotation *)annotation;
        
        if ([self canOpenUrl:@"baidumap://"]) {///跳转百度地图
            
            NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=%@&mode=driving&coord_type=bd09ll",pp.coordinate.latitude, pp.coordinate.longitude,pp.poi.name] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            
            return;
            
        }else if ([self canOpenUrl:@"iosamap://"]) {///跳转高德地图
            
            NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",@"神骑出行",@"TrunkHelper",pp.coordinate.latitude, pp.coordinate.longitude] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            
            return;
            
        }else{////跳转系统地图
            
            CLLocationCoordinate2D loc = CLLocationCoordinate2DMake(pp.coordinate.latitude, pp.coordinate.longitude);
            
            MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
            
            MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:loc addressDictionary:nil]];
            
            [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
             
                           launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,
                                           
                                           MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
            
            return;
            
        }
    }
}

-(BOOL)canOpenUrl:(NSString *)string {
    
    return  [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:string]];
    
}

/* POI 搜索回调. */

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"搜索错误：%@",error.localizedDescription);
}

-(void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response {
    if (response.pois.count == 0) {
        return;
    }
    
    //解析response获取的POI信息
    NSMutableArray *poiAnnotations = [NSMutableArray arrayWithCapacity:response.pois.count];
    
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [poiAnnotations addObject:[[POIAnnotation alloc] initWithPOI:obj]];
        
    }];
    
    //将结果加载到地图中
    [mapView_ addAnnotations:poiAnnotations];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
